package com.kunlong.util;

import app.support.exception.AppException;
import com.kunlong.base.utils.KunlongUtils;
import lombok.Data;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;

@Service
public class AttendServiceImpl implements AttendService {

	@Data
	public static class ParkingRule {
		String ruleContent;
		String remark;
		String ruleParams;
	}
	@Data
	public static class ComputeRule {
		String id;
		String ruleContent;
		String remark;
		String ruleParams;
	}
	private static ScriptEngineManager scriptManager = new ScriptEngineManager();

	public static ScriptEngine getScriptEngine() {
		return scriptManager.getEngineByName("nashorn");//得到脚本引擎
	}


	public ComputeResult compute(InputParam inputParam) {

		ComputeRule rule = new ComputeRule();
		try {
			String p = AttendServiceImpl.class.getResource("/conf/attend.js").getPath();
			File f = new File(p);
			rule.setRuleContent(FileCopyUtils.copyToString(new FileReader(f)));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		rule.setRemark("计算公式");
		rule.setRuleParams("{'maxTimesIgnore':3,'maxAvoidMinute':10}".replaceAll("'","\""));


		Assert.notNull(rule, "规则不存在");
		if(StringUtils.isEmpty(rule.getRuleContent())) {
			throw new RuntimeException("未配置计算规则");
		}
		ComputeResult computeResult = new ComputeResult();
		computeResult.setRemark(rule.getRemark());
		try {
			ScriptEngine scriptEngine = getScriptEngine();
			scriptEngine.eval(rule.getRuleContent());
			try {
				Invocable invoc = (Invocable) scriptEngine;
				invoc.invokeFunction("compute", inputParam,computeResult,rule.getRuleParams());
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("compute方法不存在");
			}
		} catch (ScriptException e) {
			throw new AppException("scriptError","脚本执行异常",e);
		}
		System.out.println(rule.getRuleContent());
		return computeResult;
	}

	public static void testCompute() {
		InputParam p = new InputParam();

		AttendParam s = new AttendParam();
		s.setDelay(12);
		s.setDay("2022-04-01");
		p.getAttendParams().add(s);

		s = new AttendParam();
		s.setDelay(2);
		s.setDay("2022-04-02");
		p.getAttendParams().add(s);

		s = new AttendParam();
		s.setDelay(10);
		s.setDay("2022-04-03");
		p.getAttendParams().add(s);
		s = new AttendParam();
		s.setDelay(4);
		s.setDay("2022-04-13");
		p.getAttendParams().add(s);
		p.setEmpId(1l);


		ComputeResult r = new AttendServiceImpl().compute(p);
		String rr = KunlongUtils.toJSONStringPretty(r);
		System.out.println(KunlongUtils.toJSONStringPretty(p));
		System.out.println(rr);

	}

	public static void main(String[] args) {
		testCompute();
	}
}
